--
-- Author:      name
-- DateTime:    2018-04-26 17:10:35
-- Description: 后台服务
local skynet = require "skynet"
require "skynet.manager"
local log = require "Log"
local config = require "configquery"
local Objects = require "Objects"
local msgpack = require "msgpack_helper"
local Message = require "backstage.Message"
local Command = require "backstage.Command"


g_objects = Objects.new()
local CMD = {}
local SOCKET = {}



function SOCKET.open(gate, fd, addr)
	log.debug("new web fd:" ..fd .." from :".. addr)
	local fd        = fd
	local gate      = gate
	skynet.call(gate, "lua", "forward", fd)

	-- msgpack.send_json_message(fd,nil , "web_test", {a=1,b=2})
end

function SOCKET.close(gate, fd)
	log.debug("web socket close", fd)
end

function SOCKET.error(gate, fd, msg)
	log.debug("web socket error", fd, msg)
end

function SOCKET.warning(gate, fd, size)
	-- size K bytes havn't send out in fd
	log.debug("web socket warning", fd, size)
end

function SOCKET.data(gate, fd, msg)
	print("__________1")
end

function CMD.socket( source, cmd, ... )
	local f = SOCKET[cmd]
	if f then
		f(source, ...)
	end
end


local function init()

	local message = Message.new()
	g_objects:add(message)
	local command = Command.new(message)
	g_objects:add(command)
	g_objects:hotfix("backstage")

	--socket
	local svr_config = config.setting_cfg["globalsvr"]
	--skynet.call(web_h, 'lua', 'start', svr_config.web_port, svr_config.web_maxclient, pbc_env)
	local conf = {
			port = svr_config.web_port,
			maxclient = svr_config.web_maxclient,
		}
	local gate = skynet.newservice("gate")
	skynet.call(gate, "lua", "open", conf)
	skynet.register_protocol{
		name = "client",
		id = skynet.PTYPE_CLIENT,
		unpack = msgpack.unpack_json_message,
		dispatch = function (fd, address, pack_id, pack_body)
			if not pack_id or not pack_body then return end
			for msg,args in pairs(pack_body) do
				local ok, result  = pcall(message:dispatch(), fd, msg, args)
				if not ok then
					log.error(result)
				end
			end
		end
	}
	-- skynet.fork(function()
	-- 	skynet.sleep(1000)
	-- 	local args = {
	-- 		{
	-- 			mid=10000001,
	-- 			card={0x01,0x02,0x03,0x04}
	-- 		},
	-- 		{
	-- 			mid=10000002,
	-- 			card={0x01,0x02,0x03,0x012,0x11}
	-- 		}			
	-- 	}
	-- 	WEB_REQUEST.web_niuniu_card( args )
	-- 	print("___@@@@@@@@@____args________________",args)
	-- end)
end


---------------------------------------------------------
-- skynet
---------------------------------------------------------

skynet.start(function()
	init()
	skynet.dispatch("lua", dispatch_command(CMD))
	skynet.register "backstage"
end)